(function ($) {
    $.fn.multiFileUploader = function(options) {
        var $this = $(this);

        var defaultOpt = {
            uploadUrl: "",
            accept: "",
            maxFileSize:-1,
            fieldName: "file",
            fileNameEdit: false, //是否选择文件后,弹出文件名修改的框
            sender: $this,
            afterUploadCallback:null,
            name: "",
            disabled:false
        }

        var tbody = $this.find("table tbody");

        var opt = $.extend({}, defaultOpt, options);

        var buildItem = function(data) {
            var tr = $("<tr></tr>");

            tr.append(
                "<td><i class=\"fileIcon fa fa-fw " + getMimeIcon(__getFileExtension(data.FileUrl), data.Mime) + "\"></i></td>");

            tr.append("<td class='filename' ><span>" + data.Title + "</span><input class=\"fileurl\" type=\"hidden\" name=\"" + opt.name + "\" value=\"" + data.FileUrl+"\"/></td>");

            tr.append(
                '<td  class="buttonlist"><span class="badge bg-info badge-view" style=\"cursor: pointer;display:none;margin-right=5px\">查看</span><span class="badge bg-red badge-del" style=\"cursor: pointer;\">删除</span></td>');

            tr.data("fileinfo-mime", data.Mime);
            tr.data("fileinfo-title", data.Title);


            return tr;
        }

        var refreshRowEvent = function(row) {
            var delBadge = $(row).find(".badge-del");
            var viewBadge = $(row).find(".badge-view");

            delBadge.click(function () {
                $(row).closest("tr").remove();
            });

            var json =row.data("fileinfo");

            viewBadge.click(function () {
                var url = $(row).find(".fileurl").val();

                WebUIJS.ShowFileViewer(url, { mime: json.Mime});
            });
        }

        var addNewItem = function(data) {
            var tr = buildItem(data);

            tbody.append(tr);

            refreshRowEvent(tr);

            $(tr).find(".badge-status").remove();
            $(tr).find(".badge-view").show();

            refreshInputFileInfo();

            return tr;
        }

        var init = function() {
            $this.find("table.filetable tbody tr").each(function (index, value) {
                var tr = $(this);

                refreshRowEvent(tr);
            });

            refreshInputFileInfo();
        }

        var refreshInputFileInfo = function () {
            var infos = [];

            $this.find("table tbody tr").each(function() {
                var mime = $(this).data("fileinfo-mime");
                var title = $(this).data("fileinfo-title");
                var url = $(this).find("input[type=hidden]").val();
                
                infos.push({
                    Mime: mime,
                    Title: title,
                    FileUrl:url
                });
            });

            $this.find(".allfileinfo").val(JSON.stringify(infos));
        }

        $this.find(".addfile").click(function () {

            if (opt.uploadUrl && opt.uploadUrl != "") {
                WebUIJS.ShowUploadFile(opt.uploadUrl,
                    {
                        accept: opt.accept,
                        fieldName: opt.fieldName,
                        maxFileSize: opt.maxFileSize,
                        onSuccess: function(ret, f) {
                            if (ret.IsSuccess) {
                                var data = {
                                    Title: f.name,
                                    Mime: f.type,
                                    FileUrl: ret.ReturnData
                                }

                                addNewItem(data);

                                WebUIJS.Toast("上传成功");

                                if (opt.afterUploadCallback) {
                                    __callBackFuncOrStr(opt.afterUploadCallback, opt.sender, [data]);
                                }

                            } else {

                                WebUIJS.Alert(data.Message);
                            }
                        },
                        onError: function() {
                            WebUIJS.Toast("上传失败");
                        },
                        onAfterSelectFile: function(file) {
                            if (opt.fileNameEdit) {
                                var fileName = confirm(f.name);

                                file.name = fileName;
                            }
                        }
                    });
            } else {
                var file = $("<input type=\"file\" style=\"display:none\" name=\"" + opt.fieldName + "\" accept=\"" + opt.accept + "\" />");

                $(file).change(function() {
                    if (this.files.length <= 0) {
                        $(this).remove();
                        return false;
                    }

                    if (opt.maxFileSize && opt.maxFileSize > 0 && this.files[0].size > opt.maxFileSize) {
                        $(this).remove();
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }
                    
                    if (opt.fileNameEdit) {
                        WebUIJS.Confirm(this.files[0].name,
                            "新文件名",
                            function (txt) {
                                var data = {
                                    Title: txt,
                                    Mime: f.type,
                                    FileUrl:""
                                }

                                var tr = addNewItem(data);

                                tr.find(".filename").append(file);

                                if (opt.afterUploadCallback) {
                                    __callBackFuncOrStr(opt.afterUploadCallback, opt.sender, [data]);
                                }
                            });
                    } else {
                        var data = {
                            Title: this.files[0].name,
                            Mime: f.type,
                            FileUrl: ""
                        }

                        var tr = addNewItem(data);

                        tr.find(".filename").append(file);

                        if (opt.afterUploadCallback) {
                            __callBackFuncOrStr(opt.afterUploadCallback, opt.sender, [data]);
                        }
                    }


                });


            }
        });

        init();
    }

    

})(jQuery);
(function($) {
    $.fn.imageCrop = function (options) {
        var defaultOpt = {
            urlOrFile:null,   //文件url或者 file 对象
            cropSize: null,  //{width:"500px",height:"500px"}
            uploadUrl: "",
            fieldName: "",
            onSuccessCallback: null,
            onFailCallback: null,
            onPreview: null,  //上传前/上传后的预览回调
            fileField: null,  //如果需要指定特定的input file,,则在此设置,但,如果是需要强制裁剪的话,不会改变该file字段的数据内容,请在onSuccessCallback中读取
            sender: $(this)
        }

        var opt = $.extend({}, defaultOpt, options);

        var croppie = null;
        var img = new Image();

        var afterImageLoad = function () {
            var rate = opt.cropSize.width / opt.cropSize.height;

            if (img.naturalWidth/img.naturalHeight == rate) { //如果比例一致,则不切图
                if (opt.onSuccessCallback) {
                    __callBackFuncOrStr(opt.onSuccessCallback,
                        opt.sender,
                        [opt.urlOrFile]);
                }

                //layer.close(index);
            }


            var imageSize = __calcImageSize(
                img.naturalWidth,
                img.naturalHeight,
                 $(window).width() * 0.4,
                 $(window).height() * 0.4
                );

            //img.width = imageSize.width ;
            //img.height = imageSize.height;

            $(img).css("width", "100%");

            var div = $("<div class=\"croptest\"></div>");
            div.append(img);
            div.css("width", imageSize.width + "px");
            div.css("height", imageSize.height + "px");

            $("body").append(div);

            layer.open({
                type:1,
                content: div,
                maxWidth: $(window).width() * 0.7,
                maxHeight: $(window).height() * 0.7,
                //area: [imageSize.width + "px", (imageSize.height+56) + "px"],
                btn: ["确定", "取消"],
                success: function () {
                    //div.append(img);
                    croppie = new Cropper(img,
                        {
                            aspectRatio: opt.cropSize.width / opt.cropSize.height,
                            modal: false,
                            //cropBoxResizable: false,
                            viewMode:0,
                            //zoomOnTouch:false
           
                        });

                    croppie.crop();

                },
                end: function() {
                    croppie.destroy();
                    div.remove();
                },
                yes: function (index, layero) {
                    var result = croppie.getCroppedCanvas();
                    
                    result.toBlob(function (blob) {
                        var file = $(opt.urlOrFile);

                        if (file.is("input[type=file]")) {
                            file = file[0].files[0];
                        } else {
                            file = file[0];
                        }

                        blob.name = file.name;
                            if (opt.onSuccessCallback) {
                                __callBackFuncOrStr(opt.onSuccessCallback,
                                    opt.sender,
                                    [blob]);
                            }

                        layer.close(index);

                        
                        },
                        "image/jpeg",1);

                    //croppie.result(
                    //    {
                    //        type: 'blob',
                    //        format: 'jpeg',
                    //        size: opt.cropSize
                    //    }).then(function (data) {
                    //        //if (typeof (data) != typeof (Blob)) {
                    //        //    data = new Blob(data, { type: "image/jpg" });
                    //        //}

                           

                    //});

                    if (opt.onPreview) {
                        var base64 = result.toDataURL("image/jpeg", 0.9);
                        __callBackFuncOrStr(opt.onPreview, opt.sender, [base64]);
                    }
                    
                },
                btn2: function(index, layero) {
                    layer.close(index);
                }
            });
        }

        
        img.onload = afterImageLoad;
        

        if (!opt.urlOrFile && typeof (opt.urlOrFile) == typeof (String)) {
            $(img).attr("src", opt.urlOrFile);
        }
        else {
            

            __onReadFile(opt.urlOrFile,
                opt.sender,
                function (evt) {
                    $(img).attr("src", evt.target.result);
                });

        }
    }

})(jQuery);
(function ($) {
    //用于处理单个文件的上传
    $.imageUploader = function (options) {
        var defaultOpt = {
            urlOrFile: "",
            forceCrop: false,
            cropSize: null,  //{width:"500px",height:"500px"}
            maxFileSize: -1,
            uploadUrl: "",
            fieldName: "",
            onAfterSelectFile:null,
            onComplete:null,
            onSuccessCallback: null,
            onFailCallback: null,
            onPreview: null,  //上传前/上传后的预览回调
            onBeforeUpload: null,
            accept:"image/*",
            //fileField: null,  //如果需要指定特定的input file,,则在此设置,但,如果是需要强制裁剪的话,不会改变该file字段的数据内容,请在onSuccessCallback中读取
            sender: $(this)
        }

        var opt = $.extend({}, defaultOpt, options);

        var autoRemoveFileField = false;

        if (!opt.urlOrFile || isEmpty(opt.urlOrFile)) {
            var file = $('<input style="display:none" accept="' + opt.accept + '" type="file" name="' + opt.fieldName + '"/>');

            $(opt.sender).closest("div").append(file);
            //$(opt.sender).closest(".control-content").append(file);
             
            opt.urlOrFile = file;

            autoRemoveFileField = true;
        }

        var uploadFile = function(f, options) {
            var file = $(opt.urlOrFile);

            if ($(opt.urlOrFile).is("input[type=file]")) {
                file = opt.urlOrFile[0].files[0];
            } else {
                if (file.length && file.length>0) {
                    file = file[0];
                }
            }

            var fileName = file.name;
            file.name = fileName.substr(0, fileName.lastIndexOf('.')) + fileName.substring(fileName.indexOf('.') + 1);
            var progress = WebUIJS.ShowProgress(file.name);



            if (opt.onBeforeUpload) {
                __callBackFuncOrStr(opt.onBeforeUpload, opt.sender, [f]);
            }

            __uploadFileToServer(f,
                options.uploadUrl,
                {
                    fieldName: options.fieldName,
                    name: file.name,
                    onProgress: function (value) {
                        progress.setProgress(value);
                    },
                    onSuccess: function (data) {
                        if (options.onSuccessCallback) {
                            __callBackFuncOrStr(options.onSuccessCallback,
                                options.sender,
                                [data, f.name]);
                        }
                        
                        progress.hide();

                    },
                    onComplete: function(data) {
                        if (opt.onCompeted) {
                            __callBackFuncOrStr(opt.onCompeted, opt.sender, [data]);
                        }

                        if (autoRemoveFileField) {
                            opt.urlOrFile.remove();
                        }
                    },
                    onError: function () {
                        if (options.onFailCallback) {
                            __callBackFuncOrStr(options.onFailCallback,
                                options.sender,
                                []);
                        }
                    }
                });
        }

        var onPreview = function(base64) {
            if (opt.onPreview) {
                __callBackFuncOrStr(opt.onPreview,
                    opt.sender,
                    [base64]);
            }
        }

        var crop = function(urlOrFile, options) {
            $(opt.sender).imageCrop({
                urlOrFile: urlOrFile,
                cropSize: options.cropSize,
                onSuccessCallback: function (blob) {
                    uploadFile(blob, options);
                },
                sender: opt.sender,
                onPreview: opt.onPreview==null?null:onPreview,
                onFailCallback: function () {
                    if (options.onFailCallback) {
                        __callBackFuncOrStr(options.onFailCallback, options.sender, []);
                    }
                }
            });
        }

        if (opt.uploadUrl && opt.uploadUrl != "") {
            if (isString(opt.urlOrFile)) {
                crop(opt.urlOrFile, opt);
            } else if ($(opt.urlOrFile).is("input[type=file]")) {
                opt.urlOrFile[0].onchange = function(event) {
                    if (this.files.length <= 0) { //未选中任何文件
                        $(this).remove();
                        return false;
                    }

                    if (opt.maxFileSize && opt.maxFileSize > 0 && opt.fileField[0].files[0].size > opt.maxFileSize) {
                        $(this).remove();
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    if (opt.onAfterSelectFile) {
                        __callBackFuncOrStr(opt.onAfterSelectFile, this, [this]);
                    }

                    var file = this.files[0];

                    try {

                        if (opt.forceCrop && opt.cropSize != null && opt.cropSize.width > 0 && opt.cropSize.height > 0
                        ) { //如果需要强制裁剪的

                            crop(file, options);
                        } else {
                            if (opt.onPreview) {
                                __onReadFile(file,
                                    opt.sender,
                                    function(evt) {
                                        __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                                    });
                            }

                            uploadFile(file, opt);
                        }

                    } catch (e) {
                        //image.attr('src', $(this).val());
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                        opt.urlOrFile.remove();
                        //return;
                    }
                }

                opt.urlOrFile.click();
            } else {
                if (opt.forceCrop && opt.cropSize != null && opt.cropSize.width > 0 && opt.cropSize.height > 0
                ) { //如果需要强制裁剪的

                    crop(opt.urlOrFile, options);
                } else {
                    if (opt.onPreview) {
                        __onReadFile(opt.urlOrFile,
                            opt.sender,
                            function(evt) {
                                __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                            });
                    }

                    uploadFile(opt.urlOrFile, opt);
                }
            }
        } else {

            var file = $(opt.urlOrFile);

            if ($(opt.urlOrFile).is("input[type=file]")) {
                file = opt.urlOrFile[0];
            } else {
                if (file.length && file.length > 0) {
                    file = file[0];
                }
            }

            file.name = opt.fieldName;

            file.onchange = function() {
                if (this.files.length <= 0) { //未选中任何文件
                    $(this).remove();
                    return false;
                }

                if (opt.maxFileSize && opt.maxFileSize > 0 && file.files[0].size > opt.maxFileSize) {
                    $(this).remove();
                    WebUIJS.Alert("文件太大,不能上传");
                    return false;
                }

                if (opt.onAfterSelectFile) {
                    __callBackFuncOrStr(opt.onAfterSelectFile, this, [this]);
                }

                try {
                    if (opt.onPreview) {
                        __onReadFile(file,
                            opt.sender,
                            function (evt) {
                                __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                            });
                    }
                } catch (e) {
                    WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                    file.remove();
                } 

            }

            file.click();
        }


        
        
    }

})(jQuery);
(function ($) {

    $.fn.multiImageUploader = function (options) {
        var $uploader = $(this);
        var defaultName = $uploader.find("input[type=hidden]").attr("name");

        var settings = $.extend({
            'uploadUrl': '',
            'disabled': false,
            'accept': "image/*",
            'maxFileSize': 0,
            'width': 120,
            'height': 120,
            'colSize': 3,
            'name': defaultName,
            'cropSize':null
        }, options);

        var __buildNewItem = function (imageUrl, name, width, height, colSize, editEnabled, deletedEnabled) {
            var buttons = "";

            if (editEnabled) {
                buttons += '<button class="btn btn-sm btn-lightyellow editimage" type="button">修改</button>';
                //buttons += '<button class="btn btn-sm btn-danger clearimage" type="button">清除</button>';
            }

            if (deletedEnabled) {
                buttons += '<button class="btn btn-sm btn-lavenderblush deleteimage" type="button">删除</button>';
            }


            var temlpate =
                '<li class="multi-image-uploader-box col-xs-' + colSize + '">' +
                '   <div class="multi-image-uploader-content">' +
                '       <div class="row multi-image-uploader-img"> <div class="multi-image-uploader-img-item" style="width:' + settings.width +'px;height:' + settings.height +'px">' +
                '           <img width="100%" height="100%" src="' + imageUrl + '" />' +
                '           <input type="hidden" name="' + name + '" value="' + imageUrl + '" />' +
                '       </div></div>' +
                '       <div class="row multi-image-uploader-button">' +
                '           <div class="col-xs-12">' +
                '               <button class="btn btn-sm btn-azure viewimage" type="button">查看</button>' +
                buttons +
                '           </div>' +
                '       </div>' +
                '       <div class="clearfix"></div>' +
                '   </div>' +
                '   <div class="clearfix" ></div > ' +
                '</li>';

            return $(temlpate);
        }

        var __refreshItemEvent = function (item) {
            var $item = $(item);
            var viewBtn = $(item).find(".viewimage");
            var editbtn = $(item).find(".editimage");
            var deleteimage = $(item).find(".deleteimage");
            var clearimage = $(item).find(".clearimage");

            var imageUrl = $item.find("input[type=hidden]").val();

            $(viewBtn).click(function () {
                WebUIJS.ShowImageViewer(imageUrl);
            });

            $(editbtn).click(function () {
                if (isEmpty(settings.uploadUrl)) { //如果uploadurl为空,则表示需要使用同步上传
                    var file = $item.find("input[type=file]");

                    if (!file || file.length <= 0) {
                        file = $('<input style="display:none" type="file" name="' + settings.name + '"/>');
                        if (settings.accept && settings.accept !== "") {
                            file.attr("accept", settings.accept);
                        }

                        file[0].onchange = function () {
                            if (this.files.length <= 0) {
                                return false;
                            }

                            if (settings.maxFileSize &&
                                settings.maxFileSize > 0 &&
                                this.files[0].size > settings.maxFileSize) {

                                WebUIJS.Alert("文件太大,不能上传");
                                return false;
                            }

                            try {
                                var reader = new FileReader();
                                reader.onload = function (evt) {
                                    $(item).find("img").attr('src', evt.target.result);
                                }

                                reader.readAsDataURL(this.files[0]);

                            } catch (e) {
                                WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                            }
                        }

                        file.insertBefore($item.find("img"));
                    }


                    file.click();
                } else {
                    $.imageUploader({
                        urlOrFile: null,
                        fieldName: settings.name,
                        maxFileSize: settings.maxFileSize,
                        forceCrop: true,
                        cropSize: settings.cropSize,
                        uploadUrl: settings.uploadUrl,
                        onSuccessCallback: function (ret) {
                            if (ret.IsSuccess) {
                                $item.find("img").attr("src", ret.ReturnData);
                                $item.find("input[type=hidden]").val(ret.ReturnData);
                            } else {
                                WebUIJS.Alert(ret.Message);
                            }
                        },
                        onPreview: function (result) {
                            //$(image).attr('src', result.data);
                        },
                        onComplete: function() {
                            $item.find("button").attr("disabled", null); //开始上传完成之后,取消禁用
                        },
                        onBeforeUpload: function() {
                            $item.find("button").attr("disabled", "disabled"); //开始上传之前,禁用按钮
                        }
                    });

                    //WebUIJS.ShowUploadFile(settings.uploadUrl,
                    //    {
                    //        maxFileSize: settings.maxFileSize,
                    //        accept: settings.accept,
                    //        onSuccess: function (ret) {
                    //            if (ret.IsSuccess) {
                    //                $item.find("img").attr("src", ret.ReturnData);
                    //                $item.find("input[type=hidden]").val(ret.ReturnData);
                    //            } else {
                    //                WebUIJS.Alert(ret.Message);
                    //            }
                    //        },
                    //        onCompleted: function () {
                    //            $item.find("button").attr("disabled", null); //开始上传完成之后,取消禁用
                    //        },
                    //        onBeforeUpload: function () {
                    //            $item.find("button").attr("disabled", "disabled"); //开始上传之前,禁用按钮
                    //        },
                    //        onError: function (ret) {
                    //            WebUIJS.Alert(ret.Message);
                    //        }
                    //    });
                }


            });

            $(deleteimage).click(function () {
                $item.remove();
            });

            $(clearimage).click(function () {
                $item.find("img").attr("src", "");
                $item.find("input[type=hidden]").val('');
                if (!settings.uploadUrl || isEmpty(settings.uploadUrl)) {
                    $item.find(":file").remove();
                }

            });

            $item.find("img").on("load", function() {
                var scaleSize = __calcImageSize(
                    this.naturalWidth,
                    this.naturalHeight,
                    $(this).parent().width(),
                    $(this).parent().height());

                this.width = scaleSize.width;
                this.height = scaleSize.height;
            });

        }

        $uploader.find(".addimage").click(function () {
            if (isEmpty(settings.uploadUrl)) {  //如果uploadurl为空,则表示需要使用同步上传
                
                var file = $('<input style="display:none" type="file" name="' + settings.name + '"/>');

                if (settings.accept && settings.accept !== "") {
                    file.attr("accept", settings.accept);
                }

                file[0].onchange = function () {
                    if (this.files.length <= 0) {
                        file.remove();
                        return false;
                    }

                    if (settings.maxFileSize && settings.maxFileSize > 0 && this.files[0].size > settings.maxFileSize) {
                        file.remove();
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    var item = $uploader.__buildNewItem("",
                        settings.name,
                        settings.width,
                        settings.height,
                        settings.colSize,
                        true,
                        true);

                    file.insertBefore(item.find("img"));

                    try {
                        var reader = new FileReader();
                        reader.onload = function (evt) {
                            $(item).find("img").attr('src', evt.target.result);

                            item.insertBefore($uploader.find(".addimage"));

                            __refreshItemEvent(item);
                        }

                        reader.readAsDataURL(this.files[0]);

                    } catch (e) {
                        //image.attr('src', $(this).val());
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                        file.remove();
                        //return;
                    }
                }

                $("body").append(file);

                file.click();
            } else {
                $.imageUploader({
                    urlOrFile: null,
                    fieldName: settings.name,
                    maxFileSize: settings.maxFileSize,
                    forceCrop: true,
                    cropSize: settings.cropSize,
                    uploadUrl: settings.uploadUrl,
                    onSuccessCallback: function (ret) {
                        if (ret.IsSuccess) {
                            var item = __buildNewItem(ret.ReturnData,
                                settings.name,
                                settings.width,
                                settings.height,
                                settings.colSize,
                                true,
                                true);

                            __refreshItemEvent(item);

                            item.insertBefore($uploader.find(".addimage"));
                        } else {
                            WebUIJS.Alert(ret.Message);
                        }
                    },
                    onPreview: function (result) {
                        //$(image).attr('src', result.data);
                    },
                    onAfterSelectFile: function(fileInput) {}
                });


                //WebUIJS.ShowUploadFile(settings.uploadUrl,
                //    {
                //        maxFileSize: settings.maxFileSize,
                //        accept: settings.accept,
                //        onSuccess: function (ret) {
                            

                //        },
                //        onCompleted: function () {

                //        },
                //        onError: function (ret) {
                //            WebUIJS.Alert(ret.Message);
                //        }
                //    });
            }

        });

        var liList = $uploader.find(".multi-image-uploader-box");
        for (var i = 0; i < liList.length; i++) {
            __refreshItemEvent(liList[i]);
        }

    };
})(jQuery);
var baiduMapTemplate =
    '<div class="panel panel-danger panel-success modalwindow locationselector" style="width: 650px">' +
        '    <div class="panel-heading">地理位置选择</div>' +
        '    <div class="panel-body" style="padding:0px;">' +
        '        <div class="panel panel-default" style="margin-bottom: 0px">' +
        '            <div class="panel-heading" style="border-radius:0px;padding: 5px 20px;">' +
        '                <div class="form-group">' +
        '                    <label class="col-sm-2 control-label" style="margin-top: 6px;">搜索:</label>' +
        '                    <div class="col-sm-10">' +
        '                        <input type="text" id="txtAutoComplete_bmap" style="width:100%;" class="form-control input-sm mapAutoComplete">' +
        '                        <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:200px;height:auto; display:none;z-index: 99999;"></div>' +
        '                    </div>' +
        '                </div>' +
        '                <div class="clearfix"></div>' +
        '            </div>' +
        '            <div class="panel-body mapContrainer" id="mapContrainer" style="padding:5px;height: 450px;">' +
        '            </div>' +
        '        </div>' +
        '    </div>' +
        '    <div class="panel-footer center-block">' +
        '        <button class="btn btn-default pull-right btnCancel" style="margin-left: 20px" type="button">取消</button>' +
        '        <button class="btn btn-primary pull-right btnOK" type="button">确定</button>' +
        '        <div class="clearfix"></div>' +
        '    </div>' +
        //'    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=NywGUL2jiY4OAwvWMobljHFT8OrHl0sK"></script>' +
        '</div>';

    
    (function ($) {
        /*
         * 选择地理位置点
         *
         * options:{
         *  initPos:{  //初始化位置, 如果传入经纬度,则定位到指定位置,如果传入的是string,则通过反查地址获取位置,再跳转
         *      lat:0,
         *      lng:o
         *  },
         *  onSuccess:function(pos){}, //如果选择了位置,则触发该回调,pos传入的参数为 {lat:0,lng:0 , loc : "116,23"}
         *  poi:[{lat:0,lng:0},{lat:0,lng:0}] , //地图上显示的标记点
         * }
         *
         *
         */
        $.fn.GeoPicker = function (options) {

            var defaultOpt = {
                initPos: null,
                onSuccess: null,
                poi: null
            }

            var opt = $.extend({}, defaultOpt, options);

            var cityName = "";

            function G(id) { 
                return document.getElementById(id);
            }

            function setInitPostion(map, container) {
                WebUIJS.Loading();
                //根据浏览器获取当前位置
                var geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(function (r) {
                    WebUIJS.CloseLoading();
                    if (this.getStatus() == '0') {
                        addMarker(r.point, map, container);
                        //alert('您的位置：' + r.point.lng + ',' + r.point.lat);
                    } else {
                        //alert('failed' + this.getStatus());
                        WebUIJS.Msg("无法获取当前位置");
                    }

                },
                    { enableHighAccuracy: true });
            }

            function setAutoComplete(map, container, inputCtrl) {

                //var ac = new BMap.Autocomplete(//建立一个自动完成的对象
                //    {
                //        "input": "txtAutoComplete_bmap",
                //        "location": map
                //    });

                var ac = new BMap.Autocomplete({ "input": G("txtAutoComplete_bmap"), "location": map});

                if (!isPoint(opt.initPos)) {
                    ac.setInputValue(opt.initPos);
                }
                ac.show();

                ac.addEventListener("onhighlight",
                    function (e) { //鼠标放在下拉列表上的事件
                        var str = "";
                        var _value = e.fromitem.value;
                        var value = "";
                        if (e.fromitem.index > -1) {
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                        value = "";
                        if (e.toitem.index > -1) {
                            _value = e.toitem.value;
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;


                        G("searchResultPanel").innerHTML = str;
                    });

                //var myValue;
                ac.addEventListener("onconfirm",
                    function (e) { //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        G("searchResultPanel").innerHTML =
                            "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                        setPlace(myValue, map, container);
                    });

                $(inputCtrl).keydown(function (event) {

                    if (event.which == 13) {
                        event.preventDefault();

                        var results = ac.getResults();

                        if (results.getNumPois() <= 0) {
                            return;
                        }

                        var poi = results.getPoi(0);

                        var myValue = poi.province + poi.city + poi.district + poi.street + poi.business;

                        $(inputCtrl).val(myValue);

                        G("searchResultPanel").innerHTML = "onconfirm<br />index = 0 <br />myValue = " + myValue;

                        setPlace(myValue, map, container, function () { WebUIJS.Toast('查找不到地点',"error")});
                    }

                });

                return ac;
            }

            function addMarker(point, map, container) {
                map.clearOverlays(); //清除地图上所有覆盖物

                map.centerAndZoom(point, 15);

                var marker = new BMap.Marker(point);
                marker.enableDragging();
                marker.addEventListener("dragend",
                    function (e) {
                        //alert("当前位置：" + e.point.lng + ", " + e.point.lat);
                    });

                map.addOverlay(marker); //添加标注

                container.data("marker", marker);

                return marker;
            }

            function setPlace(keyword, map, container, onFaild) {

                var local = new BMap.LocalSearch(map,
                    { //智能搜索
                        onSearchComplete: myFun,
                        renderOptions: { map: map, autoViewport: true }
                    });

                local.enableAutoViewport();
                local.setMarkersSetCallback(function(poi) {
                    debugger;
                    for (var i = 0; i < poi.length; i++) {
                        var item = poi[i];

                        var m = item.marker;
                        m.addEventListener("click",function () {
                            //var old = $(".locationselector").data("marker");

                            //if (old) {
                            //    map.removeOverlay(old);
                            //}

                            addKeyPoint(map, m.getPosition());

                            //$(".locationselector").data("marker", addMarker(, map, container));
                        });
                    }
                });

                function myFun() {

                    var results = local.getResults();

                    if (results.getNumPois() <= 0) {
                        if (onFaild != undefined && $.isFunction(onFaild)) {
                            onFaild();
                        }

                        return;
                    }

                    //var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果

                    map.clearOverlays();

                    //$(".locationselector").data("marker", addMarker(pp, map, container));
                }

                local.search(keyword, { forceLocal: false });
            }

            function isPoint(str) {
                if (isObject(str)) {
                    if (str.lng != undefined && str.lng != null && str.lat != undefined && str.lat != null) {
                        return true;
                    }
                } else if (isString(str)) {
                    var s = str.split(',');

                    if (s.length == 2) {
                        try {
                            if (parseFloat(s[0]) !== NaN && parseFloat(s[1]) !== NaN) {
                                return true;
                            }

                        } catch (e) {
                            return false;
                        }

                    }

                }

                return false;
            }

            function toPoint(str) {
                if (isPoint(str)) {
                    if (isObject(str)) {
                        return str;
                    } else {
                        if (isString(str)) {
                            var s = str.split(',');

                            if (s.length === 2) {
                                try {
                                    var v = new BMap.Point(parseFloat(s[0]), parseFloat(s[1]));


                                    return v;
                                } catch (e) {
                                    return null;
                                }

                            }
                        }
                    }
                }
                return null;
            }

            function addKeyPoint(map, point) {
                var old = $(".locationselector").data("marker");

                if (old) {
                    map.removeOverlay(old);
                }

                var marker = new BMap.Marker(new BMap.Point(point.lng, point.lat)/*new BMap.Point(e.point.lng, e.point.lat)*/); // 创建点
                marker.enableDragging();

                map.addOverlay(marker); //增加点
                marker.setZIndex(9999999);
                marker.setAnimation(BMAP_ANIMATION_BOUNCE);


                $(".locationselector").data("marker", marker);
            }

            function initMap() {
                var el = $(baiduMapTemplate);
                $(document).find("body").append(el);
                var auto;

                WebUIJS.ModalByElement(el,
                    function (modal) {
                        $(modal).find('.locationselector').each(function () {
                            var $this = $(this);
                            var map = new BMap.Map("mapContrainer");

                            var myCity = new BMap.LocalCity();
                            myCity.get(function (result) {
                                cityName = result.name;
                                map.setCurrentCity(result.name);
                            });

                            if (isObject(opt.initPos)) {
                                opt.initPos = new BMap.Point(opt.initPos.lng, opt.initPos.lat);
                                map.centerAndZoom(toPoint(opt.initPos), 12);   
                            }
                            else if (!opt.initPos) {
                                var myCity = new BMap.LocalCity();
                                myCity.get(function (result) {
                                    cityName = result.name;
                                    map.centerAndZoom(result.center, 12);   
                                });

                            }
                            
                            //map.centerAndZoom(toPoint(options.initPos), 12);                   // 初始化地图,设置城市和地图级别。

                            $(this).data("bmap", map);
                            $(this).data("marker", null);

                            map.enableScrollWheelZoom();
                            //var initPos = toPoint(options.InitPos)

                            if (isPoint(opt.initPos)) {
                                initMarker = addMarker(toPoint(opt.initPos), map, $this);
                            } else if (isString(opt.initPos) && opt.initPos.length > 4) {
                                setPlace(opt.initPos,
                                    map,
                                    $this,
                                    function () {
                                        WebUIJS.Alert("找不到输入的地址所对应的地理位置,当前地图将定位到本机所在GPS");
                                        setInitPostion(map, $this);
                                    });
                                //$(this).find('.mapAutoComplete').val(initPos);

                            } else {
                                setInitPostion(map, $this);
                            }

                            if (opt.poi && opt.poi.length > 0) {
                                for (var i = 0; i < opt.poi.length; i++) {
                                    var point = opt.poi[i];
                                    addMarker(point, map, $this);
                                }
                            }

                            auto=setAutoComplete(map, $this, $(this).find('.mapAutoComplete'));

                            map.addEventListener("click",
                                function (e) {
                                    addKeyPoint(map, new BMap.Point(e.point.lng, e.point.lat));

                                    //var old = $(".locationselector").data("marker");

                                    //if (old) {
                                    //    map.removeOverlay(old);
                                    //}


                                    ////map.clearOverlays(); //清除地图上所有覆盖物

                                    //var marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat)); // 创建点
                                    //marker.enableDragging();

                                    //map.addOverlay(marker); //增加点

                                    //$this.data("marker", marker);
                                });


                            map.addEventListener("zoomstart",
                                function () {
                                    $this.data("currentcenterpoint", map.getCenter());
                                });

                            map.addEventListener("zoomend",
                                function (type, target) {
                                    map.panTo($this.data("currentcenterpoint"));
                                });

                            $(this).find('.btnOK').click(function () {
                                var marker = $this.data("marker");

                                if (marker == null) {
                                    WebUIJS.Msg("请选择地理位置");
                                } else {
                                    var pos = marker.getPosition();

                                    layer.close($(this).parents(".layui-layer").data('layerindex'));

                                    if (opt.onSuccess) {
                                        opt.onSuccess({ lng: pos.lng, lat: pos.lat, loc: pos.lng + "," + pos.lat});
                                    }
                                }

                                auto.dispose();

                                map.clearOverlays();
                                $(el).remove();
                            });

                            $(this).find(".btnCancel").click(function () {
                                layer.close($(this).parents(".layui-layer").data('layerindex'));
                                map.clearOverlays();
                                auto.dispose();
                                $(el).remove();
                                
                            });
                        });
                    },
                    function (layerIndex) {
                        auto.dispose();
                        $(el).remove();
                    }
                );
            }

            if (typeof BMap === 'undefined' || BMap === null || typeof BMap.Map === 'undefined' || BMap.Map === null) {
                WebUIJS.Loading(); //动态加载百度的脚本

                var script = document.createElement("script");
                script.src = "http://api.map.baidu.com/api?v=2.0&ak=NywGUL2jiY4OAwvWMobljHFT8OrHl0sK&callback=InitializeBMap";
                document.body.appendChild(script);

                window.loadingBMapHandler=null;

                window.loadingBMapHandler = setInterval(function () {
                    if (typeof window.BMap !== 'undefined' && window.BMap !== null && typeof BMap.Map !== 'undefined' && BMap.Map !== null) {
                        clearInterval(loadingBMapHandler);
                        initMap();
                        window.loadingBMapHandler = null;
                        WebUIJS.CloseLoading();
                    }
                }, 200);
            } else {
                initMap();
            }

        }

        /*
         * 使用腾讯地图,选择地理位置点
         *
         * options:{
         *  initPos:{  //初始化位置, 如果传入经纬度,则定位到指定位置,如果传入的是string,则通过反查地址获取位置,再跳转
         *      lat:0,
         *      lng:o
         *  },
         *  onSuccess:function(pos){}, //如果选择了位置,则触发该回调,pos传入的参数为 {lat:0,lng:0}
         *  poi:[{lat:0,lng:0},{lat:0,lng:0}] , //地图上显示的标记点
         * }
         *
         *
         */
        $.fn.TencentGeoPicker = function(options) {
            var defaultOpt = {
                initPos: null,
                onSuccess: null,
                poi: null
            }

            var cityName = "";
            var markers = [];

            var opt = $.extend({}, defaultOpt, options);

            function setAutoComplete(map, container, inputCtrl) {

                //var ac = new BMap.Autocomplete(//建立一个自动完成的对象
                //    {
                //        "input": "txtAutoComplete_bmap",
                //        "location": map
                //    });

                var ap = new qq.maps.place.Autocomplete(document.getElementById('txtAutoComplete_bmap'), {
                    offset: new qq.maps.Size(0, 5),
                    location: '北京市',
                    zIndex: 100000000
                });

                var ac = new BMap.Autocomplete({ "input": G("txtAutoComplete_bmap"), "location": map });

                if (!isPoint(opt.initPos)) {
                    ac.setInputValue(opt.initPos);
                }
                ac.show();

                ac.addEventListener("onhighlight",
                    function (e) { //鼠标放在下拉列表上的事件
                        var str = "";
                        var _value = e.fromitem.value;
                        var value = "";
                        if (e.fromitem.index > -1) {
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                        value = "";
                        if (e.toitem.index > -1) {
                            _value = e.toitem.value;
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;


                        G("searchResultPanel").innerHTML = str;
                    });

                //var myValue;
                ac.addEventListener("onconfirm",
                    function (e) { //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        G("searchResultPanel").innerHTML =
                            "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                        setPlace(myValue, map, container);
                    });

                $(inputCtrl).keydown(function (event) {

                    if (event.which == 13) {
                        event.preventDefault();

                        var results = ac.getResults();

                        if (results.getNumPois() <= 0) {
                            return;
                        }

                        var poi = results.getPoi(0);

                        var myValue = poi.province + poi.city + poi.district + poi.street + poi.business;

                        $(inputCtrl).val(myValue);

                        G("searchResultPanel").innerHTML = "onconfirm<br />index = 0 <br />myValue = " + myValue;

                        setPlace(myValue, map, container, function () { WebUIJS.Toast('查找不到地点', "error") });
                    }

                });

                return ac;
            }

            function addMarker(point, map, container) {
                map.clearOverlays(); //清除地图上所有覆盖物

                map.centerAndZoom(point, 15);

                var marker = new qq.maps.Marker({
                    map: map,
                    position: point
                });

                marker.addEventListener("dragend",
                    function (e) {
                        //alert("当前位置：" + e.point.lng + ", " + e.point.lat);
                    });

                markers.push(marker);

                //container.data("marker", marker);

                return marker;
            }

            function setPlace(keyword, map, container, onFaild) {
                var latlngBounds = new qq.maps.LatLngBounds();
                var local = new qq.maps.SearchService(
                    { //智能搜索
                        complete: myFun,
                        location: keyword,
                        map: map
                    });

                function myFun(results) {

                    var pois = results.detail.pois;

                    if (pois.length <= 0) {
                        if (onFaild != undefined && $.isFunction(onFaild)) {
                            onFaild();
                        }

                        return;
                    }

                    for (var i = 0; i < markers.length; i++) {
                        markers[i].setMap(null);
                    }

                    for (var j = 0; j < pois.length; j++) {
                        var poi = pois[i];
                        latlngBounds.extend(poi.latLng);

                        var marker = addMarker(poi.latLng, map);

                        markers.push(marker);

                        marker.addEventListener("click", function () {
                            //var old = $(".locationselector").data("marker");

                            //if (old) {
                            //    map.removeOverlay(old);
                            //}

                            addKeyPoint(map, marker.getPosition());

                            //$(".locationselector").data("marker", addMarker(, map, container));
                        });
                    }

                    map.fitBounds(latlngBounds);

                    map.clearOverlays();
                }

                local.search(keyword);
            }

            function isPoint(str) {
                if (isObject(str)) {
                    if (str.lng != undefined && str.lng != null && str.lat != undefined && str.lat != null) {
                        return true;
                    }
                } else if (isString(str)) {
                    var s = str.split(',');

                    if (s.length == 2) {
                        try {
                            if (parseFloat(s[0]) !== NaN && parseFloat(s[1]) !== NaN) {
                                return true;
                            }

                        } catch (e) {
                            return false;
                        }

                    }

                }

                return false;
            }

            function toPoint(str) {
                if (isPoint(str)) {
                    if (isObject(str)) {
                        return str;
                    } else {
                        if (isString(str)) {
                            var s = str.split(',');

                            if (s.length === 2) {
                                try {
                                    var v = new TMap.LatLng(parseFloat(s[1]),parseFloat(s[0]));


                                    return v;
                                } catch (e) {
                                    return null;
                                }

                            }
                        }
                    }
                }
                return null;
            }

            function addKeyPoint(map, point) {
                var old = $(".locationselector").data("marker");

                if (old) {
                    old.setMap(null);
                }

                var marker = new qq.maps.Marker({
                    position: point,
                    map: map
                });

                //var marker = new BMap.Marker(new BMap.Point(point.lng, point.lat)/*new BMap.Point(e.point.lng, e.point.lat)*/); // 创建点
                //marker.enableDragging();
                marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                marker.setDraggable(true);

                $(".locationselector").data("marker", marker);

                return marker;
            }

            function initMap() {
                var el = $(baiduMapTemplate);
                $(document).find("body").append(el);
                var auto;

                WebUIJS.ModalByElement(el,
                    function (modal) {
                        $(modal).find('.locationselector').each(function () {
                            var $this = $(this);


                            var map = new qq.maps.Map(document.getElementById("mapContrainer"), {
                                zoom: 8,
                                center: new qq.maps.LatLng(opt.initPos.lat, opt.initPos.lng),
                                mapTypeId: qq.maps.MapTypeId.ROADMAP
                            });

                            var myCity = new BMap.LocalCity();
                            myCity.get(function (result) {
                                cityName = result.name;
                                map.setCurrentCity(result.name);
                            });

                            if (isObject(opt.initPos)) {
                                opt.initPos = new TMap.LatLng(opt.initPos.lat,opt.initPos.lng);
                                map.setCenter(toPoint(opt.initPos), 12);
                            }
                            else if (!opt.initPos) {

                                var myCity = new qq.maps.CityService();

                                myCity.setComplete(function (results) {
                                    cityName = results.detail.name;

                                    map.setCenter(results.detail.latLng);
                                });

                                myCity.searchLocalCity();
                            }

                            //map.centerAndZoom(toPoint(options.initPos), 12);                   // 初始化地图,设置城市和地图级别。

                            $(this).data("bmap", map);
                            $(this).data("marker", null);

                            //map.enableScrollWheelZoom();
                            //var initPos = toPoint(options.InitPos)

                            if (isPoint(opt.initPos)) {
                                addKeyPoint(toPoint(opt.initPos), map, $this);
                            } else if (isString(opt.initPos) && opt.initPos.length > 4) {
                                setPlace(opt.initPos,
                                    map,
                                    $this,
                                    function () {
                                        WebUIJS.Alert("找不到输入的地址所对应的地理位置,当前地图将定位到本机所在GPS");
                                        setInitPostion(map, $this);
                                    });
                                //$(this).find('.mapAutoComplete').val(initPos);

                            } else {
                                setInitPostion(map, $this);
                            }

                            if (opt.poi && opt.poi.length > 0) {
                                for (var i = 0; i < opt.poi.length; i++) {
                                    var point = opt.poi[i];
                                    addMarker(new TMap.LatLng(point.lat,point.lng), map, $this);
                                }
                            }

                            auto = setAutoComplete(map, $this, $(this).find('.mapAutoComplete'));

                            map.addEventListener("click",
                                function (e) {
                                    addKeyPoint(map, new TMap.LatLng(e.latLng.getLat(), e.latLng.getLng()));
                                });


                            map.addEventListener("idle",
                                function () {
                                    $this.data("currentcenterpoint", map.getCenter());
                                });

                            map.addEventListener("dragend",
                                function (type, target) {
                                    map.panTo($this.data("currentcenterpoint"));
                                });

                            $(this).find('.btnOK').click(function () {
                                var marker = $this.data("marker");

                                if (marker == null) {
                                    WebUIJS.Msg("请选择地理位置");
                                } else {
                                    var pos = marker.getPosition();

                                    layer.close($(this).parents(".layui-layer").data('layerindex'));

                                    if (opt.onSuccess) {
                                        opt.onSuccess({ lng: pos.getLng(), lat: pos.getLat() });
                                    }
                                }

                                auto.dispose();

                                map.clearOverlays();
                                $(el).remove();
                            });

                            $(this).find(".btnCancel").click(function () {
                                layer.close($(this).parents(".layui-layer").data('layerindex'));
                                map.clearOverlays();
                                auto.dispose();
                                $(el).remove();

                            });
                        });
                    },
                    function (layerIndex) {
                        auto.dispose();
                        $(el).remove();
                    }
                );
            }

            if (typeof qq.maps.Map === 'undefined' || qq.maps.Map === null || typeof qq.maps.Map === 'undefined' || qq.maps.Map === null) {
                WebUIJS.Loading(); //动态加载腾讯的脚本

                var script = document.createElement("script");
                script.src = "https://map.qq.com/api/js?v=2.exp&key=QUDBZ-RXZL5-ASJIL-Q2KGM-CYNHF-SHBXI&callback=InitializeBMap";
                document.body.appendChild(script);

                window.loadingBMapHandler = null;

                window.loadingBMapHandler = setInterval(function () {
                    if (typeof qq.maps.Map !== 'undefined' && qq.maps.Map !== null && typeof qq.maps.Map !== 'undefined' && qq.maps.Map !== null) {
                        clearInterval(loadingBMapHandler);
                        initMap();
                        window.loadingBMapHandler = null;
                        WebUIJS.CloseLoading();
                    }
                }, 200);
            } else {
                initMap();
            }
        }
})(jQuery);


function InitializeBMap() {
    
}


/*
本插件为配合Kugar.AdminLTE控件框架使用的表格功能,主要提供了左右两侧固定列,排序按钮功能
用于取代jqTable,由于jqTable过于复杂,列宽等不容配置,因此单独编写了这个控件,用于实现部分常用的表格功能

调用的方式:
      $("#testtb").simpleTable({
        leftFloatCol: parseInt($("#testtb").data("leftfloat")),    //左侧浮动n列,默认为0
        rightFloatCol: parseInt($("#testtb").data("rightfloat")),  //右侧浮动n列,,默认为0
        scrollY:false,                                             //是否使用高度固定的滚动条功能
        scrollHeight:0,                                            //固定的高度,单位为px,默认为0,只能是数字
      }).on("webui_table.sort",function(e,data){  
        //点击刷新按钮触发的事件data为事件内容  data.sortType 为修改后的排序方式: asc,desc,unsort 三种   data.sortKey 为排序列的key
        //请注意在这个时间中,自行增加loading防止多次出发
        var p=0;
      })
      .on("webui_table.refresh",function(e){
        //出发刷新功能的时候,触发该事件,

      }).on("webui_table.init",function(e){
          //控件初始化完成后,触发该事件
      })
      ;

      $("#testtb").simpleTable().refresh();   //该函数用于刷新表格,重新应用表格样式
      $("#testtb").simpleTable().cleanWrap();   //该函数用于清空表格样式,还原原来的表格

*/

; (function ($) {
    $.fn.simpleTable = function (options) {
        var defaults = {
            //各种参数、各种属性
            leftFloatCol: 0,
            rightFloatCol: 0,
            scrollY: false,
            scrollHeight: 200,
            autoAddRow: false
        };


        var isInitCompleted = false;

        //options合并到defaults上,defaults继承了options上的各种属性和方法,将所有的赋值给endOptions
        var endOptions = $.extend(defaults, options);

        var $table = $($(this).first());

        if (!$table.is("table.webui_table")) {
            return null;
        }

        var obj = $table.data("webui_table_object");

        if (obj) {
            return obj;
        }

        //处理内容Y轴滚动事件
        var __onScrollYHandler = function (event) {
            var st = $(this).scrollTop();

            var tmpLeft = $(this).data("leftFloatDiv");

            if (tmpLeft) {
                tmpLeft.scrollTop(st);
            }

            var tmpRight = $(this).data("rightFloatDiv");

            if (tmpRight) {
                tmpRight.scrollTop(st);
            }
        };

        var __onSortByButtonClick = function (event) {
            //排序按钮变化的顺序为: 未排序-升序--降序-未排序
            var $this = $(this);

            var newSortType = "";

            if ($this.is(".fa-sort")) { // 未排序
                $this.removeClass("fa-sort").addClass("fa-sort-amount-asc");
                newSortType = "asc";
            }
            else if ($this.is(".fa-sort-amount-asc")) {
                $this.removeClass("fa-sort-amount-asc").addClass("fa-sort-amount-desc");
                newSortType = "desc";
            }
            else if ($this.is(".fa-sort-amount-desc")) {
                $this.removeClass("fa-sort-amount-desc").addClass("fa-sort");
                newSortType = "unsort";
            }

            event.stopPropagation();

            $table.trigger("webui_table.sort",
                {
                    sortType: newSortType,
                    sortKey: $this.data("sortkey"),
                    triggerElement: this,
                });
        };

        var __onCheckboxClickHandler = function(event) {

        };

        //去除table的包装元素
        this.cleanWrap = function () {
            if (!$table.is('.wraped')) {
                return this;
            }

            var wrapper = $table.closest(".webui_table_wrapper");

            $table.insertBefore(wrapper);

            wrapper.remove();

            if (isInitCompleted) {
                $table.trigger("webui_table.cleanwrapper", this);
            }

        }

        //重新组装table
        this.refresh = function () {
            console.log("table refresh");

            this.cleanWrap();

            if ((endOptions.scrollHeight > 0 || 
                endOptions.leftFloatCol > 0 || endOptions.rightFloatCol>0)
            ) {
                var realTable = $table;

                realTable.find("td .table_column_buttonlist").each(function () {
                    var w = $(this).outerWidth();
                    $(this).closest("td").width(w);
                });

                var realTableParent = $(realTable).parent();

                var outSideBox = $(
                    "<div class=\"box no-border no-margin webui_table_wrapper hidden\"><div class=\"box-body no-padding\"></div></div>"
                );
                var outSideBoxBody = $(outSideBox).children(".box-body");

                var leftFloatQty = endOptions.leftFloatCol;
                var rightFloatQty = endOptions.rightFloatCol;

                var leftFloatDiv, rightFloatDiv;
                var leftFloatTable, rightFloatTable;

                var leftFloatTableWidth = 0,
                    rightFloatTableWidth = 0;


                if (leftFloatQty > 0 || rightFloatQty > 0) { //如果左右需要浮动列的情况下
                    if (leftFloatQty > 0) {
                        leftFloatDiv = $("<div class=\"webui_table_float_left hidden\"><table><thead></thead></table></div>");
                        leftFloatTable = $(leftFloatDiv).children("table");
                        leftFloatTable.attr("class", realTable.attr("class"));
                        leftFloatTable.removeClass("webui_table");
                    }
                    if (rightFloatQty > 0) {
                        rightFloatDiv = $("<div class=\"webui_table_float_right hidden\"><table><thead></thead></table></div>");
                        rightFloatTable = $(rightFloatDiv).children("table");
                        rightFloatTable.attr("class", realTable.attr("class"));
                        rightFloatTable.removeClass("webui_table");
                    }

                    //循环多层表头,将表头clone到左右浮动table
                    realTable.children("thead").find("tr").each(function () { //兼容多个表头行的情况
                        var headerRowMaxHeight = 0;
                        var readTableHeadRow = $(this);
                        var realTableHeadTh = $(this).find("th");

                        //计算原始表头中,当前行的最大高度
                        realTableHeadTh.each(function () {
                            if ($(this).outerHeight() > headerRowMaxHeight) {
                                headerRowMaxHeight = $(this).outerHeight();
                            }
                        });

                        if (leftFloatQty > 0) {
                            var floatThead = leftFloatTable.find("thead").first();
                            var floatHeadRow = $(this).clone(true, true);
                            floatThead.append(floatHeadRow);

                            var currentFloatHeadTotalWidth = 0;
                            var currentMapperColSpan = 0;

                            floatHeadRow.find("th").each(function (index, e) {
                                var colspan = parseIntEx($(this).attr("colspan"), 1);
                                currentMapperColSpan += colspan;
                                if (currentMapperColSpan > leftFloatQty) {
                                    $(e).remove();
                                } else {
                                    currentFloatHeadTotalWidth += $(realTableHeadTh[index]).outerWidth();
                                    $(this).height(headerRowMaxHeight);
                                    //$(this).html($(realTableHeadTh[index]).html());
                                }

                            });

                            if (leftFloatTableWidth < currentFloatHeadTotalWidth) {
                                leftFloatTableWidth = currentFloatHeadTotalWidth;
                            }

                        }

                        if (rightFloatQty > 0) {
                            var floatThead = rightFloatTable.find("thead").first();
                            var floatHeadRow = $(this).clone(true, true);
                            floatThead.append(floatHeadRow);

                            var thCount = realTable.children("thead").find("th").length - rightFloatQty;
                            var currentFloatHeadTotalWidth = 0;
                            var currentMapperColSpan = 0;

                            floatHeadRow.find("th").each(function (index, e) {
                                currentMapperColSpan += parseIntEx($(this).attr("colspan"), 1);

                                if (currentMapperColSpan <= thCount) { //删除非浮动列的表头
                                    $(e).remove();
                                } else {
                                    currentFloatHeadTotalWidth += $(realTableHeadTh[index]).outerWidth();
                                    $(this).height(headerRowMaxHeight);
                                    //$(this).html($(realTableHeadTh[index]).html());
                                }


                            });

                            if (rightFloatTableWidth < currentFloatHeadTotalWidth) {
                                rightFloatTableWidth = currentFloatHeadTotalWidth;
                            }
                        }
                    });

                    //开始计算左侧浮动列
                    if (leftFloatQty > 0) {

                        leftFloatTable.append("<tbody></tbody>");

                        outSideBoxBody.append(leftFloatDiv);

                        $(leftFloatTable).height($(realTable).outerHeight());
                        $(leftFloatTable).children("thead").height($(realTable).children("thead").height());
                    }

                    //开始计算右侧浮动列
                    if (rightFloatQty > 0) {

                        rightFloatTable.append("<tbody></tbody>");

                        outSideBoxBody.append(rightFloatDiv);

                        $(rightFloatTable).height($(realTable).outerHeight());
                        $(rightFloatTable).children("thead").height($(realTable).children("thead").height());
                    }
                }


                var realTableRows = $(realTable).children("tbody").children("tr");

                //开始复制左右浮动列的数据栏
                realTableRows.each(function (index, e) {
                    var row = $(e);
                    var tdlst = $(row).children("td");
                    var sourceHeight = $(e).height();

                    if (leftFloatTable) {
                        var r = $("<tr></tr>");

                        for (var i = 0; i < leftFloatQty; i++) {
                            r.append($(tdlst[i]).clone(true, true));

                        }
                        r.height(sourceHeight + "px");
                        leftFloatTable.append(r);
                    }

                    if (rightFloatTable) {
                        var r = $("<tr></tr>");

                        for (var i = rightFloatQty - 1; i >= 0; i--) {
                            r.append($(tdlst[tdlst.length - 1 - i]).clone(true, true));
                        }

                        r.height(sourceHeight + "px");
                        rightFloatTable.append(r);
                    }
                });

                $(outSideBoxBody).append("<div class=\"webui_table_float_tablecontent\"></div>");

                outSideBox.insertBefore(realTable);

                $(outSideBoxBody).children(".webui_table_float_tablecontent").append(realTable);

                if (outSideBox) {
                    outSideBox.removeClass("hidden");
                }

                if (leftFloatDiv) {
                    leftFloatDiv.removeClass("hidden");

                    if (leftFloatTableWidth > outSideBoxBody.width()) {
                        leftFloatTableWidth = outSideBoxBody.width();
                    }

                    $(leftFloatTable).width(leftFloatTableWidth);
                }

                if (rightFloatDiv) {
                    rightFloatDiv.removeClass("hidden");

                    if (rightFloatTableWidth > outSideBoxBody.width()) {
                        rightFloatTableWidth = outSideBoxBody.width();
                    }

                    $(rightFloatTable).width(rightFloatTableWidth);
                }

                realTable.addClass("wraped");

                if (endOptions.scrollY && endOptions.scrollHeight > 0) {
                    var scrollWidth = getScrollWidth();
                    var content = $(outSideBoxBody).children(".webui_table_float_tablecontent");

                    content.css("overflow-y", "auto").css("max-height", endOptions.scrollHeight + "px");

                    var floatDivMaxHeight = content[0].scrollWidth > content[0].clientWidth ? (endOptions.scrollHeight - scrollWidth) : endOptions.scrollHeight;

                    if (leftFloatDiv) {
                        leftFloatDiv
                            .css("max-height", floatDivMaxHeight + "px")
                            .css("overflow", "hidden");

                        content.data("leftFloatDiv", leftFloatDiv);
                    }

                    if (rightFloatDiv) {
                        rightFloatDiv
                            .css("max-height", floatDivMaxHeight + "px")
                            .css("right", content[0].scrollHeight > content[0].clientHeight ? scrollWidth : 0)
                            .css("overflow", "hidden");

                        content.data("rightFloatDiv", rightFloatDiv);
                    }

                    content.scroll(__onScrollYHandler);
                }

                outSideBoxBody.find("td .delrow").each(function () {
                    $(this).click(function () {
                        var that = $(this);
                        WebUIJS.Confirm("是否删除该行?", "删除确认", function () {
                            $(that).closest("tr").remove();
                            //.remove();
                            $table.simpleTable().refresh();
                        }
                        );
                    });
                });

                var onSortClick = debounce(200, __onSortByButtonClick);
                outSideBox.find("i.head-sort-icon").click(onSortClick);

                $(realTable).find("th").each(function (index, item) {
                    if ($(item).hasClass("selectcol")) {
                        $(item).find(":checkbox").change(function () {
                            var isChecked = $(this).is(":checked");
                            $(realTable).find("tbody tr").each(function () {
                                var checkbox = $($(this).find("td")[index]).find(".layui-form-checkbox");
                                if (isChecked !== checkbox.is(".layui-form-checked")) {
                                    checkbox.click();
                                }
                            });
                        });
                    }
                });

            }

            if (endOptions.autoAddRow) {
                WebUIJS.InitAutoAddTableRow($table, null);
            }

            if (isInitCompleted) {
                $table.trigger("webui_table.refresh", this);
            }

        }


        this.refresh();
        isInitCompleted = true;

        $table.data("webui_table_object", this);
        $table.trigger("webui_table.init", this);

        return this;
    };

    var debounce = function (idle, action) {
        var last
        return function () {
            var ctx = this, args = arguments
            clearTimeout(last)
            last = setTimeout(function () {
                action.apply(ctx, args)
            }, idle)
        }
    }
})(jQuery);

function getScrollWidth() {
    var noScroll, scroll, oDiv = document.createElement("DIV");
    oDiv.style.cssText = "position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;";
    noScroll = document.body.appendChild(oDiv).clientWidth;
    oDiv.style.overflowY = "scroll";
    scroll = oDiv.clientWidth;
    document.body.removeChild(oDiv);
    return noScroll - scroll;
}